package server;

import java.io.*;
import java.util.*;
import java.net.*;

import javax.net.ssl.*;
import msgs.*;
/**
 * Listens for client connections
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */

public class ClientListener extends Thread {
	/**
	 * Incoming message queue from the client
	 */
	protected static Vector<ClientMsg> inQ;
	private boolean go;
	//private SSLServerSocket ssock;
	//private SSLSocket sock = new SSLSocket();
	private ServerSocket ssock;
	private Socket sock;
	private ObjectInputStream ois;
	private ClientMsg cmsg;
	//private final static String KS_PATH = "server.jks"; 
	//private final static String KS_PASS = "changeit";
	//final String[] enabledCipherSuites = { "SSL_DH_anon_WITH_RC4_128_MD5" };
	
	public ClientListener(int port) { 
		inQ = new Vector<ClientMsg>();
		go = true;
	//	System.setProperty("javax.net.ssl.keyStore", KS_PATH);
		//System.setProperty("javax.net.ssl.keyStorePassword", KS_PASS);
		try {
			//SSLServerSocketFactory factory =
			//	(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
			//ssock = (SSLServerSocket) factory.createServerSocket(port);
			
			//ssock.setEnabledCipherSuites(enabledCipherSuites);
			ssock = new ServerSocket(port);
		}
		catch (IOException e) {
			go = false;
			System.err.println("Unable to open port " + port + " for listening!");
			e.printStackTrace();
		}
	}
	
	public void run() {
		while (go) {
			try {
				// process inQ
				sock = ssock.accept();
				ois = new ObjectInputStream(sock.getInputStream());
				cmsg = (ClientMsg) ois.readObject();
				inQ.add(cmsg);
				ois.close();
				//sock.close();
			}
			catch (EOFException e) {
				try {
					ois.close();
					sock.close();
				}
				catch (Exception e2) {e2.printStackTrace();}
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * Violently kills this thread
	 */
	public void killClientListener() {
		go = false;
	}
}
